﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 进货退货服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class PurchasereturnService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Purchasereturn> _purchasereturnRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public PurchasereturnService(SqlSugarRepository<Purchasereturn> purchasereturnRep, ISqlSugarClient sqlSugarClient)
    {
        _purchasereturnRep = purchasereturnRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询进货退货 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询进货退货")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<PurchasereturnOutput>> Page(PagePurchasereturnInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _purchasereturnRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Contacts.Contains(input.Keyword) || u.ContactInformation.Contains(input.Keyword) || u.ReturnedGoods.Contains(input.Keyword) || u.PreparedBy.Contains(input.Keyword) || u.Auditor.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contacts), u => u.Contacts.Contains(input.Contacts.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactInformation), u => u.ContactInformation.Contains(input.ContactInformation.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReturnedGoods), u => u.ReturnedGoods.Contains(input.ReturnedGoods.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PreparedBy), u => u.PreparedBy.Contains(input.PreparedBy.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Auditor), u => u.Auditor.Contains(input.Auditor.Trim()))
            .WhereIF(input.DocumentStatus != null, u => u.DocumentStatus == input.DocumentStatus)
            .WhereIF(input.ReturnDateRange?.Length == 2, u => u.ReturnDate >= input.ReturnDateRange[0] && u.ReturnDate <= input.ReturnDateRange[1])
            .WhereIF(input.PurchaseNumber != null, u => u.PurchaseNumber == input.PurchaseNumber)
            .WhereIF(input.Supplier != null, u => u.Supplier == input.Supplier)
            .WhereIF(input.PurchasingDepartment != null, u => u.PurchasingDepartment == input.PurchasingDepartment)
            .WhereIF(input.QuantityReturned != null, u => u.QuantityReturned == input.QuantityReturned)
            .WhereIF(input.Department != null, u => u.Department == input.Department)
            .WhereIF(input.DocumentPreparationtimeRange?.Length == 2, u => u.DocumentPreparationtime >= input.DocumentPreparationtimeRange[0] && u.DocumentPreparationtime <= input.DocumentPreparationtimeRange[1])
            .WhereIF(input.AuditTimeRange?.Length == 2, u => u.AuditTime >= input.AuditTimeRange[0] && u.AuditTime <= input.AuditTimeRange[1])
            .WhereIF(input.Purchaser != null, u => u.Purchaser == input.Purchaser)
            .LeftJoin<Commodityinformation>((u, purchaseNumber) => u.PurchaseNumber == purchaseNumber.Id)
            .LeftJoin<Vendor>((u, purchaseNumber, supplier) => u.Supplier == supplier.Id)
            .LeftJoin<PostManagement>((u, purchaseNumber, supplier, purchasingDepartment) => u.PurchasingDepartment == purchasingDepartment.Id)
            .LeftJoin<Organization>((u, purchaseNumber, supplier, purchasingDepartment, department) => u.Department == department.Id)
            .LeftJoin<UserManagement>((u, purchaseNumber, supplier, purchasingDepartment, department, purchaser) => u.Purchaser == purchaser.Id)
            .Select((u, purchaseNumber, supplier, purchasingDepartment, department, purchaser) => new PurchasereturnOutput
            {
                Id = u.Id,
                DocumentStatus = u.DocumentStatus,
                ReturnDate = u.ReturnDate,
                PurchaseNumber = u.PurchaseNumber,
                PurchaseNumberFkDisplayName = $"{purchaseNumber.ItemName}",
                Supplier = u.Supplier,
                SupplierFkDisplayName = $"{supplier.VendorName}",
                Contacts = u.Contacts,
                ContactInformation = u.ContactInformation,
                PurchasingDepartment = u.PurchasingDepartment,
                PurchasingDepartmentFkDisplayName = $"{purchasingDepartment.PostName}",
                QuantityReturned = u.QuantityReturned,
                ReturnAmount = u.ReturnAmount,
                ReturnedGoods = u.ReturnedGoods,
                PreparedBy = u.PreparedBy,
                Department = u.Department,
                DepartmentFkDisplayName = $"{department.OrganizationName}",
                DocumentPreparationtime = u.DocumentPreparationtime,
                Auditor = u.Auditor,
                AuditTime = u.AuditTime,
                Purchaser = u.Purchaser,
                PurchaserFkDisplayName = $"{purchaser.UserName}",
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取进货退货详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取进货退货详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Purchasereturn> Detail([FromQuery] QueryByIdPurchasereturnInput input)
    {
        return await _purchasereturnRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加进货退货 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加进货退货")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddPurchasereturnInput input)
    {
        var entity = input.Adapt<Purchasereturn>();
        return await _purchasereturnRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新进货退货 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新进货退货")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatePurchasereturnInput input)
    {
        var entity = input.Adapt<Purchasereturn>();
        await _purchasereturnRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除进货退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除进货退货")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletePurchasereturnInput input)
    {
        var entity = await _purchasereturnRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _purchasereturnRep.FakeDeleteAsync(entity);   //假删除
        //await _purchasereturnRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除进货退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除进货退货")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletePurchasereturnInput> input)
    {
        var exp = Expressionable.Create<Purchasereturn>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _purchasereturnRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _purchasereturnRep.FakeDeleteAsync(list);   //假删除
        //return await _purchasereturnRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataPurchasereturnInput input)
    {
        var purchaseNumberData = await _purchasereturnRep.Context.Queryable<Commodityinformation>()
            .InnerJoinIF<Purchasereturn>(input.FromPage, (u, r) => u.Id == r.PurchaseNumber)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ItemName}"
            }).ToListAsync();
        var supplierData = await _purchasereturnRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Purchasereturn>(input.FromPage, (u, r) => u.Id == r.Supplier)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var purchasingDepartmentData = await _purchasereturnRep.Context.Queryable<PostManagement>()
            .InnerJoinIF<Purchasereturn>(input.FromPage, (u, r) => u.Id == r.PurchasingDepartment)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PostName}"
            }).ToListAsync();
        var departmentData = await _purchasereturnRep.Context.Queryable<Organization>()
            .InnerJoinIF<Purchasereturn>(input.FromPage, (u, r) => u.Id == r.Department)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        var purchaserData = await _purchasereturnRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Purchasereturn>(input.FromPage, (u, r) => u.Id == r.Purchaser)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "purchaseNumber", purchaseNumberData },
            { "supplier", supplierData },
            { "purchasingDepartment", purchasingDepartmentData },
            { "department", departmentData },
            { "purchaser", purchaserData },
        };
    }
    
    /// <summary>
    /// 导出进货退货记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出进货退货记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagePurchasereturnInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportPurchasereturnOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "进货退货导出记录");
    }
    
    /// <summary>
    /// 下载进货退货数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载进货退货数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportPurchasereturnOutput>(), "进货退货导入模板", (_, info) =>
        {
            if (nameof(ExportPurchasereturnOutput.PurchaseNumberFkDisplayName) == info.Name) return _purchasereturnRep.Context.Queryable<Commodityinformation>().Select(u => $"{u.ItemName}").Distinct().ToList();
            if (nameof(ExportPurchasereturnOutput.SupplierFkDisplayName) == info.Name) return _purchasereturnRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportPurchasereturnOutput.PurchasingDepartmentFkDisplayName) == info.Name) return _purchasereturnRep.Context.Queryable<PostManagement>().Select(u => $"{u.PostName}").Distinct().ToList();
            if (nameof(ExportPurchasereturnOutput.DepartmentFkDisplayName) == info.Name) return _purchasereturnRep.Context.Queryable<TreeParentOutput>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            if (nameof(ExportPurchasereturnOutput.PurchaserFkDisplayName) == info.Name) return _purchasereturnRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入进货退货记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入进货退货记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportPurchasereturnInput, Purchasereturn>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 进货单号
                    var purchaseNumberLabelList = pageItems.Where(x => x.PurchaseNumberFkDisplayName != null).Select(x => x.PurchaseNumberFkDisplayName).Distinct().ToList();
                    if (purchaseNumberLabelList.Any()) {
                        var purchaseNumberLinkMap = _purchasereturnRep.Context.Queryable<Commodityinformation>().Where(u => purchaseNumberLabelList.Contains($"{u.ItemName}")).ToList().ToDictionary(u => $"{u.ItemName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PurchaseNumber = purchaseNumberLinkMap.GetValueOrDefault(e.PurchaseNumberFkDisplayName ?? "");
                            if (e.PurchaseNumber == null) e.Error = "进货单号链接失败";
                        });
                    }
                    // 链接 供应商
                    var supplierLabelList = pageItems.Where(x => x.SupplierFkDisplayName != null).Select(x => x.SupplierFkDisplayName).Distinct().ToList();
                    if (supplierLabelList.Any()) {
                        var supplierLinkMap = _purchasereturnRep.Context.Queryable<Vendor>().Where(u => supplierLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Supplier = supplierLinkMap.GetValueOrDefault(e.SupplierFkDisplayName ?? "");
                            if (e.Supplier == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 进货部门
                    var purchasingDepartmentLabelList = pageItems.Where(x => x.PurchasingDepartmentFkDisplayName != null).Select(x => x.PurchasingDepartmentFkDisplayName).Distinct().ToList();
                    if (purchasingDepartmentLabelList.Any()) {
                        var purchasingDepartmentLinkMap = _purchasereturnRep.Context.Queryable<PostManagement>().Where(u => purchasingDepartmentLabelList.Contains($"{u.PostName}")).ToList().ToDictionary(u => $"{u.PostName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PurchasingDepartment = purchasingDepartmentLinkMap.GetValueOrDefault(e.PurchasingDepartmentFkDisplayName ?? "");
                            if (e.PurchasingDepartment == null) e.Error = "进货部门链接失败";
                        });
                    }
                    // 链接 所在部门
                    var departmentLabelList = pageItems.Where(x => x.DepartmentFkDisplayName != null).Select(x => x.DepartmentFkDisplayName).Distinct().ToList();
                    if (departmentLabelList.Any()) {
                        var departmentLinkMap = _purchasereturnRep.Context.Queryable<TreeParentOutput>().Where(u => departmentLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Department = departmentLinkMap.GetValueOrDefault(e.DepartmentFkDisplayName ?? "");
                            if (e.Department == null) e.Error = "所在部门链接失败";
                        });
                    }
                    // 链接 进货人
                    var purchaserLabelList = pageItems.Where(x => x.PurchaserFkDisplayName != null).Select(x => x.PurchaserFkDisplayName).Distinct().ToList();
                    if (purchaserLabelList.Any()) {
                        var purchaserLinkMap = _purchasereturnRep.Context.Queryable<UserManagement>().Where(u => purchaserLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Purchaser = purchaserLinkMap.GetValueOrDefault(e.PurchaserFkDisplayName ?? "");
                            if (e.Purchaser == null) e.Error = "进货人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Purchasereturn>>();
                    
                    var storageable = _purchasereturnRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Contacts?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactInformation?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.ReturnedGoods?.Length > 2000, "退货货品长度不能超过2000个字符")
                        .SplitError(it => it.Item.PreparedBy?.Length > 32, "制单人长度不能超过32个字符")
                        .SplitError(it => it.Item.Auditor?.Length > 32, "审核人长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
